package wang.lx.mybatis.service;

import java.text.ParseException;
import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.nimbusds.jose.JOSEException;

import wang.lx.mybatis.common.JwtToken;
import wang.lx.mybatis.common.JwtUtil;
import wang.lx.mybatis.common.SysException;
import wang.lx.mybatis.entity.SysUser;

/**
 * @Description: 用户token服务接口
 * @Author: 王的世界
 * @Date: 2025/07/08 21:37:19
*/
public class SysUserTokenService implements SysUserTokenServiceI {

    @Override
    public String genUserToken(SysUser sysUser) throws JOSEException {
        JwtToken jwtToken = new JwtToken();
        Date date = new Date();
        jwtToken.setExpire_at(date.getTime() + JwtToken.LIFE);
        jwtToken.setToken(sysUser.getUserid());
        return JwtUtil.signWithJwt(JSON.toJSONString(jwtToken), JwtUtil.SECRET_KEY);
    }

    @Override
    public JwtToken getJwtToken(String jwtstr) throws ParseException, JOSEException {
        String payload = JwtUtil.verifyWithJwt(jwtstr, JwtUtil.SECRET_KEY);
        JwtToken jwtToken = JSON.parseObject(payload, JwtToken.class);
        if(System.currentTimeMillis() > jwtToken.getExpire_at())
        {
            throw new SysException("token已过期");
        }
        return jwtToken;
    }
    
}
